import React, { Component } from 'react';
import { View, Text, Image, StyleSheet, TouchableOpacity, Modal, ImageBackground, TouchableWithoutFeedback, Animated, Easing } from 'react-native'
import { pTx } from "../utils/dimensions"

export default class PlayVoice extends Component {
    constructor(props) {
        super(props);
        const [time, uri] = props.item.M?.split(' ')
        this.state = {
            loadImgIndex: 2,
            countdownTime: time / 1000,
            time: time / 1000,
            uri: uri
        }
    }

    onStopPlay = () => {
        if (this.timer) {
            clearInterval(this.timer)
            this.timer = undefined
            this.setState({
                loadImgIndex: 2,
                countdownTime: this.state.time
            })
        }
    }

    onStartPlay = async () => {
        if (this.timer === undefined) {
            this.setState({
                loadImgIndex: 0,
            })
            this.timer = setInterval(() => {
                let i = this.state.loadImgIndex + 1;
                i = i % 3;
                this.setState({
                    loadImgIndex: i,
                    countdownTime: this.state.countdownTime - 0.5
                })
                if (this.state.countdownTime < -0.5) {
                    this.onStopPlay()
                }
            }, 500);
        }
    }

    componentWillUnmount() {
        this.onStopPlay()
    }

    render() {
        return (
            <View style={[styles.playVoice, { minWidth: pTx((this.state.time > 60 ? 60 : this.state.time) * 30 / 10 + 50), flexDirection: this.props.item.S == -1 ? "row-reverse" : "row" }]}>
                <View style={[styles.imageOverflow, { transform: [{ rotateY: this.props.item.S == -1 ? "180deg" : "0deg" }] }]}>
                    <ImageBackground source={require('../assets/image/playVoice.png')}
                        style={[styles.image, { transform: [{ translateX: -pTx(this.state.loadImgIndex * 15) }, { translateY: pTx(0) }] }]}
                        resizeMode="cover" />
                </View>
                <Text style={styles.secs}>''{Math.floor(this.state.time + 1)} </Text>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    playVoice: {
        marginTop: pTx(5),
        paddingHorizontal: pTx(12),
        paddingVertical: pTx(10),
        backgroundColor: "#06C161",
        borderRadius: pTx(6),
        flexDirection: "row",
        alignItems: "center"
    },
    imageOverflow: {
        height: pTx(15),
        width: pTx(15),
        overflow: "hidden"
    },
    image: {
        width: pTx(60),
        height: pTx(15),
    },
    secs: {
        marginHorizontal: pTx(3),
        fontSize: pTx(12),
        color: "#fff"
    }
});